﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StackTrace = System.Diagnostics.StackTrace;
using System.Globalization;

namespace CognisessCommLib
{
    /// <summary>
    /// 李小栋
    /// 王龙翔
    /// </summary>
    public sealed class LogHelper
    {
        private LogHelper()
        {
        }

        public const int LOGINFOTYPE = 0;
        public const int LOGWARNTYPE = 1;
        public const int LOGERRORTYPE = 2;
        public const int LOGTRACETYPE = 3;

        private static string[] LOGSTRING = new string[]{"INFO","WARN","ERROR","TRACE"};

        /// <summary>
        /// Log Info
        /// </summary>
        /// <param name="message"></param>
        public static void Info(string message)
        {
            Write(0, message);
        }

        /// <summary>
        /// Log Warn
        /// </summary>
        /// <param name="message"></param>
        public static void Warn(string message)
        {
            Write(1, message);
        }

        /// <summary>
        /// Log Error
        /// </summary>
        /// <param name="message"></param>
        public static void Error(string message)
        {
            Write(2, message);
        }

        /// <summary>
        /// Log Trace
        /// </summary>
        /// <param name="message"></param>
        public static void Trace(string message)
        {
            Write(3, message);
        }

        /// <summary>
        /// Write Log
        /// </summary>
        /// <param name="logType"></param>
        /// <param name="message"></param>
        public static void Write(int logType, string message)
        {
            string stackmsg = getCurrentStack();
            message = LOGSTRING[logType] + ":" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss", CultureInfo.CurrentCulture) + "\r\n"
                + message + "\r\n"
                + stackmsg;
            System.Diagnostics.Trace.WriteLine(message);
        }

        private static String getCurrentStack()
        {
            string msg = "Runtime stack:\r\n";
            StackTrace stackTrace = new StackTrace(true);
            int maxStackCount = 6;

            for (int i = 3; i < stackTrace.FrameCount && i <= maxStackCount; i++)
            {
                msg += stackTrace.GetFrame(i).GetFileName() +" Method:"+ stackTrace.GetFrame(i).GetMethod().Name + ":" + stackTrace.GetFrame(i).GetFileLineNumber() + "\r\n";
            }
            return msg;

        }
    }
}
